package com.mioto.ld.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.mioto.ld.module.personal.model.User;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author mioto-qinxj
 * @date 2024/4/11
 * @desc
 */
public class BaseUtil {

    public static String createSnowflakeNo(){
        Snowflake snowflake = IdUtil.getSnowflake(1,1);
        return snowflake.nextIdStr();
    }

    /**
     * 构建用户查看数据权限
     * @return
     */
    public static Integer buildUserFilterCondition(){
        Integer roleId = getLoginUserRoleId();
        //超级管理员查看所有数据
        if (roleId== null || roleId == 1){
            return null;
        }
        return getLoginUser().getId();
    }

    /**
     * 获取登录用户信息
     * @return
     */
    public static User getLoginUser() {
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (object instanceof User){
            return (User)object;
        }
        return new User();
    }

    public static Integer getLoginUserRoleId() {
        String roleId = SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().findFirst().get().toString();
        try {
            return Integer.parseInt(roleId);
        }catch (Exception e){
            return null;
        }

    }

    public static void main(String[] args){
        System.out.println(createSnowflakeNo());
    }
}
